define(function(require,exports,module){
	require("resource/js/easyui/themes/icon.css");
	require("resource/js/easyui/easyloader.js")
	require("resource/js/component/tree.js");
	var EUtil = require("resource/js/component/easyutil.js");
	var ajax = require("resource/js/component/ajax.js");
	var alertMsg = require("resource/js/component/alerts.js");
	var myChart;
	var url='';
	var deptTopId;
	var timeType='';
	var param = {
			procKey:'',
			xType:'',
			deptId:''
		};
	 
	$("#querymonth").click(function(){//按月查
		$("a").removeClass("start");
        $(this).addClass("start");
        timeType='month';
        loadStatsData();
	});
	$("#queryweek").click(function(){//按周查
		$("a").removeClass("start");
        $(this).addClass("start");
        timeType='week';
        loadStatsData();
	});
	$("#queryday").click(function(){//按天查
		$("a").removeClass("start");
        $(this).addClass("start");
        timeType='day';
        loadStatsData();
	});
	//导出
	$("#exportBtn").click(function(){
		window.location.href = BASEPATH+"/oa/act/statistics/exportExcel.htm?procKey="+param.procKey
		 +'&xType='+param.xType+'&deptId='+param.deptId;
	});

	var dataGridConf = {
			fitColumns:true,
			autoRowHeight:false,
			pagination:false,
			striped:true,
			showFooter:true,
			columns: [[
				         {field:'xData',width:100,title:'日期',align:'center'},
				         {field:'yData',width:100,title:'天数',align:'center'}
			         ]],
			toolbar:{ 
				title:{
					_class:"",
					text:"统计报表"
				},
				btn:[	/*
				     {
				    	 iconCls: 'icon-icon1_19',
				    	 //addClass:'l-btn-display',
				    	 text:"导出Excel",
				    	 handler:function(){
				    		 window.location.href = BASEPATH+"/oa/act/statistics/exportExcel.htm?procKey="+param.procKey
				    		 +'&xType='+param.xType+'&deptId='+param.deptId;
				    	 }
				     }*/
				     ]}

	};
	/**
	 * 加载组织结构
	 */
	var loadDepts = function(callback){
		var tree = $("#deptlist").tree({
			title:"组织机构",
			searchtype:"hightlight",
			searchable:true,
			setting:{
				async:{
						enable:true,
						url:BASEPATH+"/oa/act/statistics/queryDeptsOfUsers.htm",
						dataFilter:function(a,c,f){
							if(f && f.data.length>0){
								f.data[0].open=true;
							}
							return f.data;
						}
					},
				callback:{
					onAsyncSuccess:function(event, treeId, treeNode, msg){
						var nodes =  $.fn.zTree.getZTreeObj(treeId).getNodes();
						if(nodes.length>0){
							deptTopId = nodes[0].id;
						}
						if(typeof callback == 'function'){
							callback.call(this,true); 
						}
					},
					onClick:function(event, treeId, treeNode){
						loadStatsData()
					}
				},
			},
		});
	};
	/**
	 * 加载需要统计的流程（下拉框选项数据）
	 */
	var loadProcess = function(){
		ajax.init().success(function(code,msg,data){
			 $('#procSelect').combobox('loadData',data);
			 if(data.length>0){
				 $('#procSelect').combobox('setValue',data[0].key);
			 }
		}).post(BASEPATH+"/oa/act/statistics/getStatsProcess.htm");
	}
	
	/**
	 * Echart重绘
	 */
	var setEchart = function(data){
		var procName = $('#procSelect').combobox('getText');
		var option = {
			title:{
				 text: procName+'统计',
				 left:'center',
				 //subtext:"数据来源："+(data.statsDeptName||data.statsUserName)
			},
    	    tooltip:{
	    	    	trigger:'axis',
	    	    	formatter: '{b}'+data.xTypeName+'<br/>{a}: {c}'+(data.yTypeName.split('/')[1]||'')
	    	    },
			  xAxis: {
				  boundaryGap:false,
				  name: data.xTypeName,
				  type: 'category',
				  data: data.xData,
				  axisLabel:{
					  formatter :function(value, index){
						  var str ='';
						 if(value){
							  var arr = value.split(' ');
							  if(arr[1]){
								  str += arr[1]+data.xTypeName;
							  }else{
								  str += arr[0]+data.xTypeName;
							  } 
						 }
						 return str;
					  }
				  }
		        },
		        yAxis: {
		        	name:data.yTypeName
		        },
		        series: [{
		            name: procName,
		            type: 'line',
		            data: data.yData
		        }]
			};
		myChart.setOption(option);
	};
	var setDataGrid = function(data){
		dataGridConf.toolbar.title.text = '统计报表:'+$('#procSelect').combobox('getText');
		dataGridConf.columns[0][0].title='日期/'+data.xTypeName;
		dataGridConf.columns[0][1].title=data.yTypeName;
		var rows=[];
		var ylist = data.yData;
		var xList = data.xData;
		$.each(xList,function(i,item){
			item += data.xTypeName;
			rows.push({'xData':item,'yData':ylist[i]});
		});
		dataGridConf.data = rows;
		$('#dg').datagrid(dataGridConf);
	};
	/**
	 * 加载统计数据
	 */
	var loadStatsData = function(){
		param.procKey = $('#procSelect').combobox('getValue');
		param.xType = timeType;
		if($("#deptlist") && $("#deptlist").length > 0){
			var checked = $("#deptlist").tree("tree")&&$("#deptlist").tree("tree").getSelectedNodes();
			if(checked && checked.length>0){
				param.deptId = checked[0].id;
			}else{
				param.deptId = deptTopId;
			}
		}
		myChart.showLoading();
		ajax.init().success(function(code,msg,data){
			if(code == 0){
				setEchart(data);
				myChart.hideLoading();
				setDataGrid(data);
			}
		}).error(function(code,msg,data){
			alertMsg.show(msg);
			myChart.hideLoading();
		}).post(BASEPATH+url,param);
	};
	/**
	 * 初始化静态页面
	 */
	var initCommonPage =  function(){
		//myChart = echarts.init($('#eChart')[0]);
		myChart = echarts.init(document.getElementById('eChart'));
		var defaultOption = {
			title: {
			        text: '审批统计',
			        left:'center'
			},
			tooltip:{
				trigger:'axis',
			},
			xAxis: {
				 boundaryGap:false,
			    data: []
			},
			yAxis: {},
			series: [{
			    name: '小时',
			type: 'line',
				        data: []
				    }]
		   };
	   myChart.setOption(defaultOption);
//	    $('#typeSelect').combobox({
//	    	valueField:'id',    	
//		    textField:'text' ,  
//	    	data:[{id:'day',text:'日'},{id:'week',text:'周'},{id:'month',text:'月'}],
//	    	value:'day',
//	    	onChange:function(value){
//	    		loadStatsData();
//	    	}
//	    });
	    $('#procSelect').combobox({
	    	valueField:'key',    
		    textField:'name' ,  
			onChange:function(value){
				loadStatsData(); 		
	    	}
	    });
			  
	};
	
	module.exports={
		team:function(){
			using(["datagrid","parser","combobox","textbox","echarts"],function(){
				url = '/oa/act/statistics/team.htm';
				initCommonPage();
				loadDepts(loadProcess);
			});

		},
		personal:function(){
			using(["datagrid","parser","combobox","textbox","echarts"],function(){
				url = '/oa/act/statistics/personal.htm';
				initCommonPage();
				loadProcess();
			});
		}
	};

	
});
